package cn.doitedu.rtmk.mgmt.dao;

import com.alibaba.fastjson.JSONObject;
import org.roaringbitmap.RoaringBitmap;
import org.springframework.stereotype.Repository;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.sql.*;

@Repository
public class RuleMetaDao {
    Connection connection;
    PreparedStatement preparedStatement;
    PreparedStatement preparedStatement2;
    public RuleMetaDao() throws SQLException {
        connection = DriverManager.getConnection("jdbc:mysql://doitedu:3306/doti34", "root", "root");
        preparedStatement = connection.prepareStatement("select dynamic_tag_groovy_code from rule_model_resource where rule_model_id = ?");
        preparedStatement2 = connection.prepareStatement("insert into rule_instance_resource values (?,?,?,?,?,?,?,?,?)");
    }

    public String findGroovyCodeByModelId(String ruleModelId) throws SQLException {
        preparedStatement.setString(1,ruleModelId);
        ResultSet resultSet = preparedStatement.executeQuery();
        resultSet.next();
        String groovyCode = resultSet.getString("dynamic_tag_groovy_code");

        return groovyCode;
    }


    public void insertRuleInstanceResources(RoaringBitmap crowedBitmap, JSONObject ruleInstanceParams,String groovyCode) throws SQLException, IOException {

        preparedStatement2.setString(1,ruleInstanceParams.getString("rule_instance_id"));
        preparedStatement2.setString(2,ruleInstanceParams.getString("rule_model_id"));
        preparedStatement2.setString(3,(ruleInstanceParams.toJSONString()));

        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        DataOutputStream dataout = new DataOutputStream(baout);
        crowedBitmap.serialize(dataout);
        preparedStatement2.setBytes(4,baout.toByteArray());
        preparedStatement2.setString(5,groovyCode);

        preparedStatement2.setInt(6,1);
        preparedStatement2.setTimestamp(7,new Timestamp(System.currentTimeMillis()));
        preparedStatement2.setTimestamp(8,new Timestamp(System.currentTimeMillis()));
        preparedStatement2.setString(9,"nana");

        preparedStatement2.execute();

    }
}
